<?php

/*
 * 心愿相关日志表
 * @auth bzyy
 * 2015-6-16 14:33:16
 */

class WishlogModel extends BaseModel
{
	var $table  = 'wish_log';
	
	/*
	 * 随机生成一个心愿号
	 * @auth bzyy
	 * 2015-6-16 15:03:56
	 * 
	 * 格式xin
	 * 15061915-----xxx
	 */
	public function randsn()
	{
		$pre = date('ymdH');
		$min = date('i');
		$second = date('s');
		$rand = rand(1, 9999);
		
		$now = time();
		
		$x1 = ($min+$second)%10;
		$x2 = $rand%10;
		$x3 = $now%10;
		
		$sql = "select count(*) as c from ".DB_PREFIX.$this->table;
		$c = $this->getOne($sql);
		
		$c_str = str_pad($c+1, 5,'0',STR_PAD_LEFT );
		
		$sn = "{$pre}{$c_str}{$x1}{$x2}{$x3}";
		
		$sql = "select count(*) as c from ".DB_PREFIX.$this->table ." where out_trade_no='{$sn}'";
		
		$cc = $this->getOne($sql);
		if($cc)
		{
			return $this->randsn();
		}
		
		return $sn; 
	}
	
	/*
	 * 添加一个支付记录
	 * @auth bzyy
	 * 2015-6-16 15:31:12
	 */
	public function add($data)
	{
		if(empty($data['wish_id']))
		{
			$this->_errors['wish_id'] = '数据格式有误';
			return false;
		}
		
		//价钱
		$data['donate_price'] = floatval($data['donate_price']);
		if($data['donate_price']<0)
		{
			$this->_errors['donate_price'] = '支付价格无效';
			return false;
		}
		
		//检测心愿的有效性
		$model = m('wish');
		$info = $model->infoOk($data['wish_id']);
		if($info === false)
		{
			$this->_errors['error'] = $model->_errors;
			return false;
		}
		
		//支付类型的正确性
		
		$data['status'] = 0;
		$data['donate_time'] = 0;
		$data['sn'] = $this->randsn();
		return parent::add($data);
	}
	
	/*
	 * 对支付的一个更新
	 * @auth bzyy
	 * 2015-6-16 16:31:47
	 */
	public function payed($sn,$money)
	{
		$info = $this->find("sn='{$sn}'");
		if(empty($info))
		{
			$this->_errors['error'] = '支付信息不存在';
			return false;
		}
		if($info['donate_time']>0)
		{
			$this->_errors['error'] = '已经支付过了';
			return false;
		}
		
		$edit_data = array('donate_time'=>time(),'status'=>1);
		$f = $this->edit("sn='{$sn}'", $edit_data);
		if(!$f)
		{
			$this->_errors['error'] = '更新支付状态时候出错';
			return false;
		}
		
		$wish_id = $info['wish_id'];
		
		//支付当前的记录
		$sql = "select sum(donate_price) as price from ".DB_PREFIX.$this->table." where status='1' and wish_id='{$wish_id}' ";
		$money = $this->getOne($sql);
		
		
		//更新到对应的希望记录
		
		//必要的时候要生成对应的订单
		return true;
		
	}
	
	/*
	 * 必要的时候可能要生成订单
	 * @auth bzyy
	 * 2015-6-16 17:50:57
	 * 
	 * 其他的缺货等的异常处理
	 * 
	 */
	protected function corder()
	{
		//生成订单
		//填充对应的物流地址等信息
		//库存的减少
		//商家的通知
	}
	
}



?>